package com.frxuexi.base.utils

import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import java.util.concurrent.atomic.AtomicBoolean

//解决数据倒灌
class SingleLiveEvent<T>:MutableLiveData<T>() {

    val pending=AtomicBoolean(false)

    override fun observe(owner: LifecycleOwner, observer: Observer<in T>) {
        if(hasActiveObservers()){
            throw IllegalArgumentException("有多个")
        }

        super.observe(owner){
            if(pending.compareAndSet(true,false)){
                observer.onChanged(it)
            }
        }
    }

    override fun postValue(value: T) {
        pending.set(true)
        super.postValue(value)
    }
}